<script setup lang="ts">
import { ref, computed, nextTick } from 'vue';
import { uploadImage } from '@/app/api/system';
import { onLoad } from '@dcloudio/uni-app';
import { redirect, img, goback } from '@/utils/common';
import { t } from '@/locale';
import { addShop, getShopDetail } from '@/app/api/rent';
import manifestJson from '@/manifest.json';
import { getAddressByLatlng } from '@/app/api/system';

const formData: any = ref({
	id: 0,
	store_name: '',
	store_contact: '',
	store_mobile: '',
	trade_time: '',
	start_hour: '',
	start_minute: '',
	end_hour: '',
	end_minute: '',
	province_name: '',
	city_name: '',
	district_name: '',
	province_id: '',
	city_id: '',
	district_id: '',
	area: '',
	address: '',
	store_licence: [],
	store_logo: [],
	latitude: '',
	longitude: ''
});
const areaRef = ref();
const formRef: any = ref(null);
const source = ref('');
const btnDisabled = ref(false);
const isSelectAddress = ref(false);
const isSelectMap = ref(2); // 值为1，该地址需要有经纬度，反之不需要
const from = ref('');
const wxPrivacyPopupRef: any = ref(null);
onLoad((data: any) => {
	isSelectMap.value = data.isSelectMap || '';
	from.value = data.from;
	if (data.name) {
		if (uni.getStorageSync('addressInfo')) {
			Object.assign(formData.value, uni.getStorageSync('addressInfo'));
		}
		formData.value.address = data.name;
		getAddress(data.latng);
		var tempArr = getQueryVariable('latng').split(',');
		formData.value.latitude = tempArr[0];
		formData.value.longitude = tempArr[1];
	} else if (data.id) {
		getShopDetail({ store_id: data.id }).then((res: any) => {
			res.data && Object.assign(formData.value, res.data);
		});
	}
	source.value = data.source || '';
	// #ifdef MP
	nextTick(() => {
		if (wxPrivacyPopupRef.value) wxPrivacyPopupRef.value.proactive();
	});
	// #endif
});

const rules = computed(() => {
	return {
		store_name: {
			type: 'string',
			required: true,
			message: t('namePlaceholder'),
			trigger: ['blur', 'change']
		},
		store_mobile: [
			{
				validator(rule: any, value: any, callback: any) {
					console.log(value);
					let mobile = /^1[3-9]\d{9}$/;
					if (!mobile.test(value)) {
						callback(new Error(t('mobileError')));
					} else {
						callback();
					}
				}
			}
		],
		location: {
			validator() {
				let bool = true;
				if (uni.$u.test.isEmpty(formData.value.area) && uni.$u.test.isEmpty(formData.value.address)) {
					bool = false;
				}
				return bool;
			},
			message: t('selectAreaPlaceholder')
		}
	};
});
//获取详细地址
const getAddress = (latlng: any) => {
	getAddressByLatlng({ latlng }).then((res: any) => {
		if (res.data) {
			console.log(res.data);
			formData.value.area = '';
			formData.value.area += res.data.province != undefined ? res.data.province : '';
			formData.value.area += res.data.city != undefined ? '' + res.data.city : '';
			formData.value.area += res.data.district != undefined ? '' + res.data.district : '';

			// formData.value.addressName = formData.value.address.replace(/-/g, '');
			// formData.value.area = res.data.province + res.data.city + res.data.district || res.data.address;

			formData.value.province_id = res.data.province_id != undefined ? res.data.province_id : 0;
			formData.value.city_id = res.data.city_id != undefined ? res.data.city_id : 0;
			formData.value.district_id = res.data.district_id != undefined ? res.data.district_id : 0;
			formData.value.province_name = res.data.province_id != undefined ? res.data.province : 0;
			formData.value.city_name = res.data.city_id != undefined ? res.data.city : 0;
			formData.value.district_name = res.data.district_id != undefined ? res.data.district : 0;
		} else {
			uni.showToast({ title: res.msg, icon: 'none' });
		}
	});
};
const selectArea = () => {
	isSelectAddress.value = true;
	areaRef.value.open();
};

const areaSelectComplete = (event: any) => {
	formData.value.province_id = event.province?.id || 0;
	formData.value.city_id = event.city?.id || 0;
	formData.value.district_id = event.district?.id || 0;
	formData.value.province_name = event.province?.name || '';
	formData.value.city_name = event.city?.name || 0;
	formData.value.district_name = event.district?.name || 0;
	formData.value.area = `${event.province?.name || ''}${event.city?.name || ''}${event.district?.name || ''}`;
	isSelectAddress.value = false;
};

const operateLoading = ref(false);
const save = () => {
	// const save = formData.value.id ? editShop : addShop;
	const save = addShop;
	formRef.value.validate().then(() => {
		if (operateLoading.value) return;
		operateLoading.value = true;

		btnDisabled.value = true;

		// formData.value.address = formData.value.area + formData.value.addressName;
		formData.value.trade_time = `${formData.value.start_hour}:${formData.value.start_minute}~ ${formData.value.end_hour}:${formData.value.end_minute}`;
		formData.value.store_licence = formData.value.store_licence[0];
		formData.value.store_logo = formData.value.store_logo.join(',');
		if (!formData.value.store_licence) {
			uni.showToast({ title: '请上传营业执照', icon: 'none' });
			return;
		}
		if (!formData.value.address) {
			uni.showToast({ title: '请选择门店地址', icon: 'none' });
			return;
		}
		save(formData.value)
			.then((res: any) => {
				operateLoading.value = false;
				setTimeout(() => {
					btnDisabled.value = false;
					redirect({ url: from.value === 'order' ? '/addon/shop/pages/order/payment' : '/app/pages/rent/index', mode: 'redirectTo' });
				}, 1000);
			})
			.catch(() => {
				operateLoading.value = false;
				btnDisabled.value = false;
			});
	});
};

// 选择地址
const chooseLocation = () => {
	// #ifdef MP
	uni.chooseLocation({
		success: (res) => {
			res.latitude && (formData.value.latitude = res.latitude);
			res.longitude && (formData.value.longitude = res.longitude);
			res.address && (formData.value.area = res.address);
			res.name && (formData.value.address = res.name);
			if (res.latitude && res.longitude) {
				let latng = res.latitude + ',' + res.longitude;
				getAddress(latng);
			}
		},
		fail: (res) => {
			// 在隐私协议中没有声明chooseLocation:fail api作用域
			if (res.errMsg && res.errno) {
				if (res.errno == 104) {
					let msg = '用户未授权隐私权限，选择位置失败';
					uni.showToast({ title: msg, icon: 'none' });
				} else if (res.errno == 112) {
					let msg = '隐私协议中未声明，打开地图选择位置失败';
					uni.showToast({ title: msg, icon: 'none' });
				} else {
					uni.showToast({ title: res.errMsg, icon: 'none' });
				}
			}
		}
	});
	// #endif

	// #ifdef H5
	var urlencode = formData.value;
	uni.setStorageSync('addressInfo', urlencode);
	let backurl = location.origin + location.pathname + '?source=' + source.value;
	if (isSelectMap.value) {
		backurl = backurl + '&isSelectMap=' + isSelectMap.value;
	}
	window.location.href =
		'https://apis.map.qq.com/tools/locpicker?search=1&type=0&backurl=' + encodeURIComponent(backurl) + '&key=' + manifestJson.h5.sdkConfigs.maps.qqmap.key + '&referer=myapp';
	// #endif
};

const getQueryVariable = (variable: any) => {
	var query = window.location.search.substring(1);
	var vars = query.split('&');
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split('=');
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return false;
};
const licenceListPreview = computed(() => {
	return formData.value.store_licence.map((item) => {
		console.log(img(item));
		return { url: img(item) };
	});
});
const logoListPreview = computed(() => {
	console.log(formData.value.store_logo);
	return formData.value.store_logo.map((item) => {
		return { url: img(item) };
	});
});

const afterRead = (event: any) => {
	uploadImage({
		filePath: event.file.url,
		name: 'file'
	}).then((res) => {
		formData.value.store_licence[0] = res.data.url;
	});
};
const afterLogoRead = (event: any) => {
	event.file.forEach((item) => {
		uploadImage({
			filePath: item.url,
			name: 'file'
		}).then((res) => {
			if (formData.value.store_logo.length < 9) {
				formData.value.store_logo.push(res.data.url);
			}
		});
	});
};
const deletePic = (event: any) => {
	formData.value.store_licence.splice(event.index, 1);
};
const deleteLogoPic = (event: any) => {
	formData.value.store_logo.splice(event.index, 1);
};
</script>

<template>
	<view class="bg-[var(--page-bg-color)] min-h-[100vh] overflow-hidden address-edit" :style="themeColor()">
		<u-form labelPosition="left" :model="formData" errorType="toast" :rules="rules" ref="formRef">
			<view class="sidebar-margin card-template mt-[var(--top-m)] py-[20rpx]">
				<view>
					<u-form-item label="门店信息" prop="store_name" labelWidth="200rpx">
						<u-input
							fontSize="28rpx"
							v-model.trim="formData.store_name"
							border="none"
							clearable
							maxlength="25"
							placeholderStyle="color: #888"
							placeholder="请输入门店名称"
						/>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item label="联系人" prop="store_contact" labelWidth="200rpx">
						<u-input
							fontSize="28rpx"
							v-model.trim="formData.store_contact"
							maxlength="11"
							border="none"
							clearable
							placeholder="请输入联系人名称"
							placeholderStyle="color: #888"
						/>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item label="联系人手机号" prop="store_mobile" labelWidth="200rpx">
						<u-input
							fontSize="28rpx"
							v-model.trim="formData.store_mobile"
							maxlength="11"
							border="none"
							clearable
							placeholder="请输入手机号码"
							placeholderStyle="color: #888"
						/>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item label="营业时间" prop="trade_time" labelWidth="200rpx">
						<view class="flex items-center"><view class="w-[170rpx] flex items-center">
							<u-input fontSize="28rpx" v-model.trim="formData.start_hour" border="none" placeholder="时" placeholderStyle="color: #888" inputAlign="center" />
							<text class="pb-[10rpx]">:</text>
							<u-input fontSize="28rpx" v-model.trim="formData.start_minute" border="none" placeholder="分" placeholderStyle="color: #888" inputAlign="center" />
						</view>
						<text class="mx-[16rpx]">~</text>
						<view class="w-[170rpx] flex items-center">
							<u-input fontSize="28rpx" v-model.trim="formData.end_hour" border="none" placeholder="时" placeholderStyle="color: #888" inputAlign="center" />
							<text class="pb-[10rpx]">:</text>
							<u-input fontSize="28rpx" v-model.trim="formData.end_minute" border="none" placeholder="分" placeholderStyle="color: #888" inputAlign="center" />
						</view></view>

					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item label="门店地址" prop="area" labelWidth="200rpx">
						<view class="flex justify-between items-center flex-1 h-[52rpx]" @click="chooseLocation">
							<view class="text-[28rpx] text-[#303133] leading-[1.4]" v-if="formData.area">
								{{ formData.area }}
							</view>
							<view class="text-[#888] text-[28rpx]" v-else></view>
							<view class="flex items-center">
								<text class="nc-iconfont nc-icon-dizhiguanliV6xx text-[32rpx] mr-[4rpx] text-[#EF000C]"></text>
								<text class="text-[24rpx] whitespace-nowrap text-[#EF000C]">定位</text>
							</view>
						</view>
					</u-form-item>
				</view>
				<view class="mt-[16rpx]">
					<u-form-item label="详细地址" prop="address" labelWidth="200rpx">
						<u-input fontSize="28rpx" v-model="formData.address" border="none" clearable maxlength="120" placeholder="请填写详细地址" placeholderStyle="color: #888" />
					</u-form-item>
				</view>
			</view>
			<view class="sidebar-margin card-template mt-[var(--top-m)] py-[50rpx]">
				<view>
					<view class="text-[28rpx] flex items-center">
						<text>*营业执照</text>
					</view>
					<view class="mt-[30rpx]">
						<u-upload :fileList="licenceListPreview" @afterRead="afterRead" @delete="deletePic" :maxCount="1" />
					</view>
				</view>
				<view class="mt-16rpx">
					<view class="text-[28rpx] flex items-center">
						<text>环境展示-最多9张图片</text>
					</view>
					<view class="mt-[30rpx]">
						<u-upload :fileList="logoListPreview" @afterRead="afterLogoRead" @delete="deleteLogoPic" multiple :maxCount="9" />
					</view>
				</view>
			</view>
		</u-form>
		<view class="w-full footer">
			<view class="py-[var(--top-m)] px-[var(--sidebar-m)] footer w-full fixed bottom-0 left-0 right-0 box-border">
				<button
					hover-class="none"
					class="primary-btn-bg !text-[#fff] h-[80rpx] leading-[80rpx] rounded-[100rpx] text-[26rpx] font-500"
					@click="save"
					:disabled="btnDisabled"
					:loading="operateLoading"
					:class="{ 'opacity-50': btnDisabled }"
				>
					{{ t('save') }}
				</button>
			</view>
		</view>
		<area-select ref="areaRef" @complete="areaSelectComplete" :area-id="formData.district_id || formData.city_id" />
		<!-- #ifdef MP-WEIXIN -->
		<!-- 小程序隐私协议 -->
		<wx-privacy-popup ref="wxPrivacyPopupRef"></wx-privacy-popup>
		<!-- #endif -->
	</view>
</template>

<style lang="scss" scoped>
.address-edit :deep(.u-form-item__body__left__content__label) {
	font-size: 28rpx !important;
}

.address-edit :deep(.u-form-item__body__right) {
	display: flex;
}

.footer {
	height: calc(100rpx + var(--top-m) + var(--top-m) + constant(safe-area-inset-bottom)) !important;
	height: calc(100rpx + var(--top-m) + var(--top-m) + env(safe-area-inset-bottom)) !important;
}
</style>
<style lang="scss"></style>
